//
//  UIImageView+QTAdd.m
//  Pods
//
//  Created by 张俊博 on 16/8/26.
//
//

#import "UIImageView+QTAdd.h"
#import "CircleProgressLayer.h"
#import "NSObject+QTAdd.h"
#import <objc/runtime.h>

static char const * const kCircleProgressLayer    =   "kCircleProgressLayer";

@implementation UIImageView (QTAdd)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [UIImageView swizzleInstanceMethod:@selector(layoutSubviews) with:@selector(qt_layoutSubviews)];
    });
}

- (CircleProgressLayer *)progressLayer {
    CircleProgressLayer *layer = objc_getAssociatedObject(self, kCircleProgressLayer);
    if (!layer) {
        layer = [[CircleProgressLayer alloc] init];
        objc_setAssociatedObject(self, kCircleProgressLayer, layer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    return layer;
}

- (void)qt_layoutSubviews {
    CircleProgressLayer *layer = objc_getAssociatedObject(self, kCircleProgressLayer);
    if (layer) {
        layer.position = (CGPoint){CGRectGetMidX(self.layer.bounds), CGRectGetMidY(self.layer.bounds)};
    }
    [self qt_layoutSubviews];
}

- (void)setProgress:(CGFloat)progress {
    if (progress > 0 && progress < 1) {
        self.progressLayer.position = (CGPoint){CGRectGetMidX(self.layer.bounds), CGRectGetMidY(self.layer.bounds)};
        self.progressLayer.value = progress;
        [self.layer addSublayer:self.progressLayer];
        
    } else {
        [self.progressLayer removeFromSuperlayer];
        objc_setAssociatedObject(self, kCircleProgressLayer, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}

- (CGFloat)progress {
    return self.progressLayer.value;
}

- (void)setBaseTintColor:(UIColor *)baseTintColor{
    self.progressLayer.baseTintColor = baseTintColor;
}

- (UIColor *)baseTintColor {
    return self.progressLayer.baseTintColor;
}

- (void)setProgressTintColor:(UIColor *)progressTintColor{
    self.progressLayer.progressTintColor = progressTintColor;
}

- (UIColor *)progressTintColor {
    return self.progressLayer.progressTintColor;
}

- (void)setTextColor:(UIColor *)textColor{
    self.progressLayer.textColor = textColor;
}

- (UIColor *)textColor {
    return self.progressLayer.textColor;
}

- (void)setFontSize:(CGFloat)fontSize {
    self.progressLayer.fontSize = fontSize;
}

- (CGFloat)fontSize {
    return self.progressLayer.fontSize;
}

- (void)setProgressSize:(CGFloat)progressSize {
    self.progressLayer.progressSize = progressSize;
}

- (CGFloat)progressSize {
    return self.progressLayer.progressSize;
}

@end

